package com.aixingfu.sports.ui.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.aixingfu.sports.Adapter.GridImageServiceAdapter;
import com.aixingfu.sports.MVP.contract.MemberCardListContract;
import com.aixingfu.sports.MVP.contract.MobileAndIdContract;
import com.aixingfu.sports.MVP.contract.RetrievePwdContract;
import com.aixingfu.sports.MVP.contract.ServiceApplyContract;
import com.aixingfu.sports.MVP.contract.UploadContract;
import com.aixingfu.sports.MVP.presenter.MemberCardListPresenter;
import com.aixingfu.sports.MVP.presenter.MobileAndIdPresenter;
import com.aixingfu.sports.MVP.presenter.RetrievePwdPresenter;
import com.aixingfu.sports.MVP.presenter.ServiceApplyPresenter;
import com.aixingfu.sports.MVP.presenter.UploadPresenter;
import com.aixingfu.sports.Model.CodeModel;
import com.aixingfu.sports.Model.MemberCardListModel;
import com.aixingfu.sports.Model.MobileAndIdModel;
import com.aixingfu.sports.Model.RetrievePwdModel;
import com.aixingfu.sports.Model.ServiceApplyModel;
import com.aixingfu.sports.Model.UserUploadModel;
import com.aixingfu.sports.R;
import com.aixingfu.sports.bean.EvaluateBean;
import com.aixingfu.sports.bean.EvaluateFlexBean;
import com.aixingfu.sports.view.BottomDialog;
import com.aixingfu.sports.view.FullyGridLayoutManager;
import com.aixingfu.sports.view.PopMemberCardListCheckChooseID;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.google.android.flexbox.FlexboxLayout;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.orie.librarybase.base.BaseActivity;
import com.orie.librarybase.utils.CountDownTimerUtils;
import com.orie.librarybase.utils.UserUtils;
import com.vondear.rxtool.RxRegTool;
import com.vondear.rxtool.view.RxToast;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

//会员服务申请
@Route(path = "/main/ApplyServicesActivity")
public class ApplyServicesActivity extends BaseActivity implements MobileAndIdContract.MyView, MemberCardListContract.MyView, RetrievePwdContract.MyView, ServiceApplyContract.MyView, BottomDialog.OnBottomMenuItemClickListener, UploadContract.MyView {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ed_phone)
    EditText edPhone;
    @BindView(R.id.tv_getcode)
    TextView tvGetcode;
    @BindView(R.id.tv_card_name)
    TextView tvCardName;
    @BindView(R.id.ll_certificates)
    LinearLayout llCertificates;
    @BindView(R.id.ed_code)
    EditText edCode;

    @BindView(R.id.ed_member_consultant)
    EditText edMemberConsultant;
    @BindView(R.id.tv_member_name)
    TextView tvMemberName;
    @BindView(R.id.tv_member_code)
    TextView tvMemberCode;
    @BindView(R.id.flexboxLayout)
    FlexboxLayout flexboxLayout;
    @BindView(R.id.ed_client)
    EditText edClient;
    @BindView(R.id.service_flexboxLayout)
    FlexboxLayout serviceFlexboxLayout;
    @BindView(R.id.member_flexboxLayout)
    FlexboxLayout memberFlexboxLayout;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.ed_explain)
    EditText edExplain;
    @BindView(R.id.recycle_other)
    RecyclerView recycleOther;
    private MobileAndIdPresenter mobileAndIdPresenter;
    private MemberCardListPresenter memberCardListPresenter;
    private PopMemberCardListCheckChooseID popMemberCardListCheckChooseID;
    private List<MemberCardListModel.DataBean> memberCardList;
    private RetrievePwdPresenter retrievePwdPresenter;
    private String codedata;
    private List<EvaluateBean> mList = new ArrayList();
    private List<EvaluateBean> evaluateBeans = new ArrayList();
    private List<EvaluateFlexBean> serviceList = new ArrayList();
    private List<EvaluateFlexBean> serviceListData = new ArrayList();
    private List<EvaluateFlexBean> memberList = new ArrayList();
    private List<EvaluateFlexBean> memberListData = new ArrayList();
    private ServiceApplyPresenter serviceApplyPresenter;
    private String member_id = "";
    private String phone = "";
    private String code = "";
    private String cardName = "";
    private String memberConsultant = "";
    private String client = "";
    private String memberString = "";
    private String explain = "";
    private String memberCode = "";
    private List<String> memberDatas = new ArrayList<>();
    private BottomDialog bottomDialog;
    private boolean hasPermission = false;
    private static final int REQUEST_TAKE_PHOTO = 0;// 拍照
    private static final int REQUEST_CROP = 1;// 裁剪
    private static final int SCAN_OPEN_PHONE = 2;// 相册
    private static final int REQUEST_PERMISSION = 100;
    private Uri imgUri; // 拍照时返回的uri
    private Uri mCutUri;// 图片裁剪时返回的uri
    private File imgFile;// 拍照保存的图片文件

    private UploadPresenter uploadPresenter;
    private GridImageServiceAdapter gridImageAdapter;
    private String path;
    private List<String> imgList = new ArrayList();
    private String otherUri= "";
    private String jsonString;
    @Override
    protected int provideContentViewId() {
        return R.layout.activity_apply_services;
    }

    public static void startActivityByRoute() {
        ARouter.getInstance().build("/main/ApplyServicesActivity").navigation();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        tvTitle.setText("会员服务申请表");
        edPhone.addTextChangedListener(new EditChangedListener());
        mobileAndIdPresenter = new MobileAndIdPresenter();
        mobileAndIdPresenter.attachView(this);
        memberCardListPresenter = new MemberCardListPresenter();
        memberCardListPresenter.attachView(this);
        retrievePwdPresenter = new RetrievePwdPresenter();
        retrievePwdPresenter.attachView(this);
        serviceApplyPresenter = new ServiceApplyPresenter();
        serviceApplyPresenter.attachView(this);
        uploadPresenter = new UploadPresenter();
        uploadPresenter.attachView(this);
        mList.add(new EvaluateBean("亲临", "0"));
        mList.add(new EvaluateBean("电话", "1"));
        mList.add(new EvaluateBean("委托", "2"));
        for (int i = 0; i < mList.size(); i++) {
            addChildToFlexboxLayout(mList.get(i));
        }
        setServiceFlexboxLayoutData();
        setMemberFlexboxLayoutData();
        bottomDialog = new BottomDialog(this, R.layout.dialog_bottom_layout, new int[]{R.id.pick_photo_album, R.id.pick_photo_camera, R.id.pick_photo_cancel});
        bottomDialog.setOnBottomMenuItemClickListener(this);
        initWidget();
    }

    public void setServiceFlexboxLayoutData() {
        serviceList.add(new EvaluateFlexBean("其他", "0"));
        serviceList.add(new EvaluateFlexBean("转课", "1"));
        serviceList.add(new EvaluateFlexBean("转卡", "2"));
        serviceList.add(new EvaluateFlexBean("转店", "3"));
        serviceList.add(new EvaluateFlexBean("经理赠送天数", "4"));
        serviceList.add(new EvaluateFlexBean("总监赠送天数", "5"));
        serviceList.add(new EvaluateFlexBean("老会员介绍新会员赠送天数", "6"));
        serviceList.add(new EvaluateFlexBean("请假", "7"));
        serviceList.add(new EvaluateFlexBean("延期开卡", "8"));
        serviceList.add(new EvaluateFlexBean("私教课升级", "9"));
        serviceList.add(new EvaluateFlexBean("退费", "10"));
        for (int i = 0; i < serviceList.size(); i++) {
            addChildToFlexboxLayoutData(serviceList.get(i));
        }
    }

    //多选
    public void setMemberFlexboxLayoutData() {
        memberList.add(new EvaluateFlexBean("其他原因", "0"));
        memberList.add(new EvaluateFlexBean("交通不便", "1"));
        memberList.add(new EvaluateFlexBean("没有时间", "2"));
        memberList.add(new EvaluateFlexBean("外派出差", "3"));
        memberList.add(new EvaluateFlexBean("健康原因", "4"));
        memberList.add(new EvaluateFlexBean("家人反对", "5"));
        memberList.add(new EvaluateFlexBean("服务质量", "6"));
        memberList.add(new EvaluateFlexBean("课程问题", "7"));
        memberList.add(new EvaluateFlexBean("环境设备", "8"));
        memberList.add(new EvaluateFlexBean("已参加别家会所", "9"));
        for (int i = 0; i < memberList.size(); i++) {
            addChildToFlexboxLayoutMember(memberList.get(i));
        }
    }

    /**
     * 添加孩子到布局中 单选
     */
    private void addChildToFlexboxLayout(final EvaluateBean bean) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_evaluate, null);
        TextView tv = view.findViewById(R.id.tv);
        tv.setText(bean.name);
        view.setTag(bean);
        if (bean.checked) {
            tv.setBackgroundResource(R.drawable.shape_btn_y);
            tv.setTextColor(this.getResources().getColor(R.color.white));
        } else {
            tv.setBackgroundResource(R.drawable.shape_btn_n);
            tv.setTextColor(this.getResources().getColor(R.color.textColor));
        }
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (EvaluateBean labelBean : mList) {
                    if (!labelBean.equals(bean)) {
                        labelBean.checked = false;
                        evaluateBeans.remove(labelBean);
                    } else {
                        if (bean.checked == true) {
                            labelBean.checked = false;
                            evaluateBeans.remove(labelBean);
                        } else {
                            labelBean.checked = true;
                            evaluateBeans.add(labelBean);
                        }
                    }
                }
                checkLabeel();
                if (evaluateBeans.size() != 0) {
                    if ("2".equals(evaluateBeans.get(0).getReason_type())) {
                        edClient.setEnabled(true);
                    } else {
                        edClient.setEnabled(false);
                    }
                }

            }

        });
        flexboxLayout.addView(view);
    }

    /**
     * 添加孩子到布局中 单选
     */
    private void addChildToFlexboxLayoutData(final EvaluateFlexBean bean) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_evaluate, null);
        TextView tv = view.findViewById(R.id.tv);
        tv.setText(bean.name);
        view.setTag(bean);
        if (bean.checked) {
            tv.setBackgroundResource(R.drawable.shape_btn_y);
            tv.setTextColor(this.getResources().getColor(R.color.white));
        } else {
            tv.setBackgroundResource(R.drawable.shape_btn_n);
            tv.setTextColor(this.getResources().getColor(R.color.textColor));
        }
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (EvaluateFlexBean labelBean : serviceList) {
                    if (!labelBean.equals(bean)) {
                        labelBean.checked = false;
                        serviceListData.remove(labelBean);
                    } else {
                        if (bean.checked == true) {
                            labelBean.checked = false;
                            serviceListData.remove(labelBean);
                        } else {
                            labelBean.checked = true;
                            serviceListData.add(labelBean);
                        }
                    }
                }
                checkLabeelService();
            }

        });
        serviceFlexboxLayout.addView(view);
    }

    private void checkLabeel() {
        flexboxLayout.removeAllViews();
        for (EvaluateBean labelBean : mList) {
            addChildToFlexboxLayout(labelBean);
        }
    }

    private void checkLabeelService() {
        serviceFlexboxLayout.removeAllViews();
        for (EvaluateFlexBean labelBean : serviceList) {
            addChildToFlexboxLayoutData(labelBean);
        }
    }

    /**
     * 添加孩子到布局中 多选
     */
    private void addChildToFlexboxLayoutMember(final EvaluateFlexBean bean) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_evaluate, null);
        TextView tv = view.findViewById(R.id.tv);
        tv.setText(bean.name);
        view.setTag(bean);
        if (bean.checked) {
            tv.setBackgroundResource(R.drawable.shape_btn_y);
            tv.setTextColor(this.getResources().getColor(R.color.white));
        } else {
            tv.setBackgroundResource(R.drawable.shape_btn_n);
            tv.setTextColor(this.getResources().getColor(R.color.textColor));
        }
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bean.checked == true) {
                    memberListData.remove(bean);
                } else {
                    memberListData.add(bean);
                }
                bean.checked = !bean.checked;
                checkLabeel1();

            }
        });
        memberFlexboxLayout.addView(view);
    }

    private void checkLabeel1() {
        memberFlexboxLayout.removeAllViews();
        for (EvaluateFlexBean labelBean : memberList) {
            addChildToFlexboxLayoutMember(labelBean);
        }
    }

    public void getMobileAndId(String mobile) {
        if (mobileAndIdPresenter.isViewAttached()) {
            HashMap<String, String> map = new HashMap<>();
            map.put("mobile", mobile);
            mobileAndIdPresenter.getMobileAndId(map);
        }
    }

    public void getMemberCardList(String member_id) {
        if (memberCardListPresenter.isViewAttached()) {
            HashMap<String, String> map = new HashMap<>();
            map.put("member_id", member_id);
            memberCardListPresenter.getMemberCardList(map);
        }
    }

    public void getServiceApply() {
        if (serviceApplyPresenter.isViewAttached()) {

            HashMap<String, String> map = new HashMap<>();
            map.put("member_mobile", phone);
            map.put("verify_code", code);
            map.put("member_id", member_id);
            map.put("create_id", UserUtils.getEmployeeid(ApplyServicesActivity.this));
            map.put("member_card_type", cardName);
            map.put("member_card_number", memberCode);
            map.put("member_consultant", memberConsultant);
            map.put("service_request_reason_description", explain);
            map.put("service_request_reason_type", memberString);
            if (evaluateBeans.size() != 0) {
                map.put("contact_type", evaluateBeans.get(0).getReason_type());
            }
//            else {
//                map.put("contact_type", "");
//            }
            map.put("contact_info", client);
            if (serviceListData.size() != 0) {
                map.put("service_request_type", serviceListData.get(0).getReason_type());
            }

//            else {
//                map.put("service_request_type", "");
//            }
            if (imgList.size() != 0){
                jsonString = JSON.toJSONString(imgList);
                map.put("upload_pic_path", jsonString);
            }
            serviceApplyPresenter.getServiceApply(map);
        }

    }

    @Override
    public void showToast(String msg, String state) {

    }

    @Override
    public void setUpload(UserUploadModel data) {
        if (data.getCode() == 1) {
            otherUri = data.getData();
            imgList.add(otherUri);

            RxToast.normal(ApplyServicesActivity.this, data.getMessage()).show();
        }else {
            RxToast.normal(ApplyServicesActivity.this, data.getMessage()).show();
        }
    }

    @Override
    public void setFailed(String msg) {

    }

    @Override
    public void setServiceApply(ServiceApplyModel data) {
        if (data.getCode() == 1) {
            RxToast.normal(ApplyServicesActivity.this, data.getMessage()).show();
            ARouter.getInstance().build("/main/MainActivity").navigation();
        } else {
            RxToast.normal(ApplyServicesActivity.this, data.getMessage()).show();
        }
    }

    @Override
    public void setCode(CodeModel data) {
        if (data.getCode() == 1) {
            codedata = String.valueOf(data.getData());
//            edCode.setText(codedata);
        } else {
            RxToast.normal(ApplyServicesActivity.this, data.getMessage()).show();
        }
    }

    @Override
    public void setRetievePwd(RetrievePwdModel data) {
    }

    @Override
    public void setMemberCardList(MemberCardListModel data) {
        if (data.getCode() == 1) {
            memberCardList = data.getData();
            popMemberCardListCheckChooseID = new PopMemberCardListCheckChooseID(ApplyServicesActivity.this, memberCardList);
            popMemberCardListCheckChooseID.setTagTxt("请选择")//设置顶部title的内容
                    .setButtomTxt("取消")//设置底部按钮内容
                    .setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//单选
            //单选
            popMemberCardListCheckChooseID.setOnEventLisenter(positionList -> {
                popMemberCardListCheckChooseID.dismiss();
                tvCardName.setText(memberCardList.get(positionList.get(0)).getCard_name());
                tvMemberCode.setText(memberCardList.get(positionList.get(0)).getCard_number());
                edMemberConsultant.setText(memberCardList.get(positionList.get(0)).getName());
            });
        }
    }

    @Override
    public void setMobileAndId(MobileAndIdModel data) {
        if (data.getCode() == 1) {
            tvMemberName.setText(data.getData().getUsername());
            member_id = data.getData().getMember_id();
            getMemberCardList(member_id);
        } else {
            RxToast.normal(ApplyServicesActivity.this, data.getMessage()).show();
        }
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void hideLoading() {
        dismissLoadingDialog();
    }

    @Override
    public Context getMyContext() {
        return this;
    }

    @Override
    public void onBottomMenuItemClick(BottomDialog dialog, View view) {
        switch (view.getId()) {
            case R.id.pick_photo_album:
                checkPermissions();
                Toast.makeText(ApplyServicesActivity.this, "从相册选取", Toast.LENGTH_SHORT).show();
                if (hasPermission) {
                    openGallery();
                }
                break;
            case R.id.pick_photo_camera:
                checkPermissions();
                Toast.makeText(ApplyServicesActivity.this, "拍照", Toast.LENGTH_SHORT).show();
                if (hasPermission) {
                    takePhone();
                }
                break;
        }
    }

    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, SCAN_OPEN_PHONE);
    }

    // 拍照
    private void takePhone() {
        // 要保存的文件名
        String time = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(new Date());
        String fileName = "photo_" + time;
        // 创建一个文件夹
        String path = Environment.getExternalStorageDirectory() + "/take_photo";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        // 要保存的图片文件
        imgFile = new File(file, fileName + ".jpeg");
        // 将file转换成uri
        // 注意7.0及以上与之前获取的uri不一样了，返回的是provider路径
        imgUri = getUriForFile(this, imgFile);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 添加Uri读取权限
        intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
        // 或者
        grantUriPermission("com.aixingfu.sports", imgUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        // 添加图片保存位置
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
        startActivityForResult(intent, REQUEST_TAKE_PHOTO);
    }

    // 从file中获取uri
    // 7.0及以上使用的uri是contentProvider content://com.rain.takephotodemo.FileProvider/images/photo_20180824173621.jpg
    // 6.0使用的uri为file:///storage/emulated/0/take_photo/photo_20180824171132.jpg
    private static Uri getUriForFile(Context context, File file) {
        if (context == null || file == null) {
            throw new NullPointerException();
        }
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(context.getApplicationContext(), "com.aixingfu.sports.fileprovider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//
//        if (resultCode == RESULT_OK) {
//            switch (requestCode) {
//                // 裁剪后设置图片
//                case REQUEST_CROP:
//                    try {
//                        String realPathFromURI = getRealFilePath(ApplyServicesActivity.this, mCutUri);
//                        File mfile = new File(realPathFromURI);
//                        userUploadPresenter.getUserUpload(mfile);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
////                    Log.e(TAG, "onActivityResult: imgUri:REQUEST_CROP:" + mCutUri.toString());
//                    break;
//                // 打开图库获取图片并进行裁剪
//                case SCAN_OPEN_PHONE:
////                    Log.e(TAG, "onActivityResult: SCAN_OPEN_PHONE:" + data.getData().toString());
//                    cropPhoto(data.getData(), false);
//                    break;
//            }
//        }
//    }

    /**
     * uri转path
     */
    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) {
            return null;
        }
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    // 图片裁剪
    private void cropPhoto(Uri uri, boolean fromCapture) {
        Intent intent = new Intent("com.android.camera.action.CROP"); //打开系统自带的裁剪图片的intent

        // 注意一定要添加该项权限，否则会提示无法裁剪
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        intent.setDataAndType(uri, "image/*");
        intent.putExtra("scale", true);
        if (Build.MANUFACTURER.equals("HUAWEI")) {
            intent.putExtra("aspectX", 9998);
            intent.putExtra("aspectY", 9999);
        } else {
            // 设置裁剪区域的宽高比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
        }
        // 设置裁剪区域的宽度和高度
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);

        // 取消人脸识别
        intent.putExtra("noFaceDetection", true);
        // 图片输出格式
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        // 若为false则表示不返回数据
        intent.putExtra("return-data", false);

        // 指定裁剪完成以后的图片所保存的位置,pic info显示有延时
        if (fromCapture) {
            // 如果是使用拍照，那么原先的uri和最终目标的uri一致,注意这里的uri必须是Uri.fromFile生成的
            mCutUri = Uri.fromFile(imgFile);
        } else { // 从相册中选择，那么裁剪的图片保存在take_photo中
            String time = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(new Date());
            String fileName = "photo_" + time;
            File mCutFile = new File(Environment.getExternalStorageDirectory() + "/take_photo", fileName + ".jpeg");
            if (!mCutFile.getParentFile().exists()) {
                mCutFile.getParentFile().mkdirs();
            }
            mCutUri = Uri.fromFile(mCutFile);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mCutUri);
        Toast.makeText(this, "剪裁图片", Toast.LENGTH_SHORT).show();
        // 以广播方式刷新系统相册，以便能够在相册中找到刚刚所拍摄和裁剪的照片
        Intent intentBc = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intentBc.setData(uri);
        this.sendBroadcast(intentBc);
        startActivityForResult(intent, REQUEST_CROP); //设置裁剪参数显示图片至ImageVie
    }

    private void checkPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查是否有存储和拍照权限
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                    && checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                    ) {
                hasPermission = true;
            } else {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, REQUEST_PERMISSION);
            }
        } else {
            hasPermission = true;
        }
    }

    class EditChangedListener implements TextWatcher {
        private CharSequence temp; // 监听前的文本
        private int editStart; // 光标开始位置
        private int editEnd; // 光标结束位置

        // 输入文本之前的状态
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            temp = s;
        }

        // 输入文字中的状态，count是一次性输入字符数
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
//			if (charMaxNum - s.length() <= 5) {
//				tip.setText("还能输入" + (charMaxNum - s.length()) + "字符");
//			}

        }

        // 输入文字后的状态
        @Override
        public void afterTextChanged(Editable s) {
            int length = s.length();
            String mobile = s.toString();
            /** 得到光标开始和结束位置 ,超过最大数后记录刚超出的数字索引进行控制 */
            if (length == 11) {
                getMobileAndId(mobile);
            }
        }
    }

    ;

    @Override
    protected void initEvent() {

    }

    @Override
    protected void beforeInit() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.iv_back, R.id.tv_getcode, R.id.ll_certificates, R.id.tv_submit})
    public void onViewClicked(View view) {
        String mobile = edPhone.getText().toString();
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_getcode:
                if (TextUtils.isEmpty(mobile) || !RxRegTool.isMobileSimple(mobile)) {
                    RxToast.normal(ApplyServicesActivity.this, "请输入手机号").show();
                } else {
                    CountDownTimerUtils countDownTimerUtils = new CountDownTimerUtils(ApplyServicesActivity.this, tvGetcode, 60000, 1000);
                    countDownTimerUtils.start();
                    getCode(mobile);
                }
                break;
            case R.id.ll_certificates:
                if (TextUtils.isEmpty(mobile) || !RxRegTool.isMobileSimple(mobile)) {
                    RxToast.normal(ApplyServicesActivity.this, "请输入正确的手机号").show();
                } else {
                    hideIputKeyboard();
                    if (popMemberCardListCheckChooseID != null) {
                        popMemberCardListCheckChooseID.showPop(tvCardName);
                    }
                }
                break;
            case R.id.tv_submit:
                memberDatas.clear();
                phone = edPhone.getText().toString();
                code = edCode.getText().toString();
                cardName = tvCardName.getText().toString();
                memberConsultant = edMemberConsultant.getText().toString();
                client = edClient.getText().toString();
                explain = edExplain.getText().toString();
                memberCode = tvMemberCode.getText().toString();
                if (memberListData.size() != 0) {
                    for (int i = 0; i < memberListData.size(); i++) {
                        memberDatas.add(memberListData.get(i).getReason_type());
                    }
                    memberString = JSON.toJSONString(memberDatas);
                } else {
                    memberString = "";
                }
                if (TextUtils.isEmpty(phone) || !RxRegTool.isMobileSimple(phone)) {
                    RxToast.normal(ApplyServicesActivity.this, "请输入正确的手机号").show();
                } else if (TextUtils.isEmpty(code)) {
                    RxToast.normal(ApplyServicesActivity.this, "请输入验证码").show();
                } else if (TextUtils.isEmpty(cardName)) {
                    RxToast.normal(ApplyServicesActivity.this, "请选择卡名称").show();
                } else if (TextUtils.isEmpty(memberConsultant)) {
                    RxToast.normal(ApplyServicesActivity.this, "请输入会籍顾问").show();
                } else {
                    getServiceApply();
                }

//                String jsonString = JSON.toJSONString(evaluateBeans);
//                String serviceString = JSON.toJSONString(serviceListData);


                break;
        }
    }

    public void getCode(String mobile) {
        if (retrievePwdPresenter.isViewAttached()) {
            HashMap<String, String> map = new HashMap<>();
            map.put("mobile", mobile);
            map.put("type", "findpwd");
            retrievePwdPresenter.getCode(map);
        }
    }

    //关闭软键盘
    public void hideIputKeyboard() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                InputMethodManager mInputKeyBoard = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                if (getCurrentFocus() != null) {
                    mInputKeyBoard.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                }
            }
        });
    }
    private GridImageServiceAdapter.onAddPicClickListener onAddPicClickListener = new GridImageServiceAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            //第一种方式，弹出选择和拍照的dialog
            showPop(SUMBER);
        }
    };
    private List<LocalMedia> selectList = new ArrayList<>();
    private int maxSelectNumber = 5;
    private int sumber;
    private int SUMBER = 1;
    private PopupWindow pop;
    private int maxSelectNum = 5;
    List<LocalMedia> images;

    private void initWidget() {
//        mRecyclerView.setLayoutManager(new LinearLayoutManager(ChannelContractActivity.this, LinearLayoutManager.HORIZONTAL, false));
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        int spanCount = 3; // 3 columns
        int spacing = 30; // 50px
        boolean includeEdge = false;
        recycleOther.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));
        recycleOther.setLayoutManager(manager);

        gridImageAdapter = new GridImageServiceAdapter(this, onAddPicClickListener);
        gridImageAdapter.setList(selectList);
        gridImageAdapter.setSelectMax(maxSelectNumber);
        recycleOther.setAdapter(gridImageAdapter);
        gridImageAdapter.setOnDelItemClickListener(new GridImageServiceAdapter.OnDelItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                imgList.remove(position);
                selectList.remove(position);
                gridImageAdapter.setList(selectList);
                gridImageAdapter.notifyItemRemoved(position);
                gridImageAdapter.notifyDataSetChanged();
            }
        });
        gridImageAdapter.setOnItemClickListener(new GridImageServiceAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(MainActivity.this).externalPicturePreview(position, "/custom_file", selectList);
                            PictureSelector.create(ApplyServicesActivity.this).externalPicturePreview(position, selectList);
                            break;
                        case 2:
                            // 预览视频
                            PictureSelector.create(ApplyServicesActivity.this).externalPictureVideo(media.getPath());
                            break;
                        case 3:
                            // 预览音频
                            PictureSelector.create(ApplyServicesActivity.this).externalPictureAudio(media.getPath());
                            break;
                    }
                }
            }
        });
        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    PictureFileUtils.deleteCacheDirFile(ApplyServicesActivity.this);
                } else {
                    Toast.makeText(ApplyServicesActivity.this,
                            getString(R.string.picture_jurisdiction), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }
    private void showPop(final int sumber) {
        this.sumber = sumber;
        View bottomView = View.inflate(ApplyServicesActivity.this, R.layout.layout_bottom_dialog, null);
        TextView mAlbum = (TextView) bottomView.findViewById(R.id.tv_album);
        TextView mCamera = (TextView) bottomView.findViewById(R.id.tv_camera);
        TextView mCancel = (TextView) bottomView.findViewById(R.id.tv_cancel);

        pop = new PopupWindow(bottomView, -1, -2);
        pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        pop.setOutsideTouchable(true);
        pop.setFocusable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        pop.setAnimationStyle(R.style.main_menu_photo_anim);
        pop.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);

        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int i = view.getId();
                if (i == R.id.tv_album) {//相册
                    if (sumber == SUMBER) {
                        PictureSelector.create(ApplyServicesActivity.this)
                                .openGallery(PictureMimeType.ofImage())
                                .compress(true)
                                .maxSelectNum(maxSelectNum)
                                .minSelectNum(1)
                                .imageSpanCount(4)
                                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                                .enableCrop(true)// 是否裁剪 true or false
                                .compress(true)// 是否压缩 true or false
                                .selectionMode(PictureConfig.MULTIPLE)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                    } else {
                        PictureSelector.create(ApplyServicesActivity.this)
                                .openGallery(PictureMimeType.ofImage())
                                .compress(true)
                                .maxSelectNum(maxSelectNum)
                                .minSelectNum(1)
                                .imageSpanCount(4)
                                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                                .enableCrop(true)// 是否裁剪 true or false
                                .compress(true)// 是否压缩 true or false
//                                .compressSavePath(getCompressPath())//压缩图片自定义保存地址
                                .selectionMode(PictureConfig.MULTIPLE)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                    }
// 进入相册 以下是例子：用不到的 api 可以不写
                } else if (i == R.id.tv_camera) {//拍照
                    PictureSelector.create(ApplyServicesActivity.this)
                            .openCamera(PictureMimeType.ofImage())
                            .compress(true)
//                            .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                            .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                            .enableCrop(true)// 是否裁剪 true or false
                            .compress(true)// 是否压缩 true or false
                            .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                            .forResult(PictureConfig.CHOOSE_REQUEST);

                } else if (i == R.id.tv_cancel) {//取消
                    //closePopupWindow();

                }
                closePopupWindow();
            }
        };

        mAlbum.setOnClickListener(clickListener);
        mCamera.setOnClickListener(clickListener);
        mCancel.setOnClickListener(clickListener);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    images = PictureSelector.obtainMultipleResult(data);

                    if (selectList.size()+images.size() > 5){
                        RxToast.normal(ApplyServicesActivity.this, "最多上传5张照片").show();
                    }else {
                        for (int i = 0; i < images.size(); i++) {
                            path = images.get(i).getPath();
                            File mfile = new File(path);
                            uploadPresenter.getUpload(mfile);
                        }
                        selectList.addAll(images);
//                    selectList = PictureSelector.obtainMultipleResult(data);
                        // 例如 LocalMedia 里面返回三种path
                        // 1.media.getPath(); 为原图path
                        // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                        // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                        // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                        gridImageAdapter.setList(selectList);
                        gridImageAdapter.notifyDataSetChanged();
                    }

//
                    break;

                // 拍照并进行裁剪
                case REQUEST_TAKE_PHOTO:
//                    Log.e(TAG, "onActivityResult: imgUri:REQUEST_TAKE_PHOTO:" + imgUri.toString());
                    cropPhoto(imgUri, true);
                    break;
                // 裁剪后设置图片
                case REQUEST_CROP:
                    try {
                        String realPathFromURI = getRealFilePath(ApplyServicesActivity.this, mCutUri);
                        File mfile = new File(realPathFromURI);
                        uploadPresenter.getUpload(mfile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
//                    Log.e(TAG, "onActivityResult: imgUri:REQUEST_CROP:" + mCutUri.toString());
                    break;
                // 打开图库获取图片并进行裁剪
                case SCAN_OPEN_PHONE:
//                    Log.e(TAG, "onActivityResult: SCAN_OPEN_PHONE:" + data.getData().toString());
                    cropPhoto(data.getData(), false);
                    break;
            }
        }
    }
    public void closePopupWindow() {
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
            pop = null;
        }
    }
}
